<template>
  <AiGenerating v-if="loading" class="ai-loading"/>
  <div v-else class="practice-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar
        title="AI练习"
        left-text="返回"
        left-arrow
        @click-left="goBack"
    />

    <!-- 题目组件 -->
    <question-component
        v-if="currentQuestion"
        :question="currentQuestion"
        :show-correct="showCorrect"
        :user-answer="currentAnswer"
        @update:answer="handleAnswerUpdate"
        @submit="checkAnswer"
    />

    <!-- 底部操作栏 -->
    <div class="action-bar" v-if="!showCorrect">
      <van-button
          plain
          size="large"
          @click="showExplanation"
      >
        解析
      </van-button>
      <van-button
          type="primary"
          size="large"
          @click="checkAnswer"
          :disabled="!currentAnswer"
      >
        完成答题
      </van-button>
    </div>
    <div class="action-bar" v-else>
      <van-button
          plain
          size="large"
          @click="showExplanation"
      >
        解析
      </van-button>
      <van-button
          type="primary"
          size="large"
          @click="goNextQuestion"
      >
        下一题
      </van-button>
    </div>

    <!-- 解析弹窗 -->
    <van-popup
        v-model:show="showExplanationPopup"
        round
        position="bottom"
        :style="{ height: '60%' }"
    >
      <div class="explanation-container">
        <h3>题目解析</h3>
        <div class="explanation-content">
          <p><strong>正确答案：</strong>
            {{ formatAnswer(currentQuestion?.answers) }}
          </p>
          <p><strong>你的答案：</strong>
            {{ currentAnswer ? formatAnswer(currentAnswer) : '未回答' }}
          </p>
          <p><strong>解析：</strong>{{ currentQuestion?.explanation || '暂无解析' }}</p>
        </div>
        <div class="explanation-actions">
          <van-button type="primary" block @click="showExplanationPopup = false">
            关闭
          </van-button>
        </div>
      </div>
    </van-popup>

    <!-- 完成弹窗 -->
    <van-dialog
        v-model:show="showCompletionDialog"
        title="练习完成"
        show-cancel-button
        confirm-button-text="查看结果"
        cancel-button-text="返回首页"
        @confirm="goToResult"
        @cancel="goBack"
    >
      <div class="completion-content">
        <p>您已完成所有练习！</p>
        <p>正确率: {{ currentQuestion?.correctRate || 0 }}%</p>
      </div>
    </van-dialog>
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref} from 'vue';
import {useRouter} from 'vue-router';
import {showConfirmDialog} from 'vant';
import QuestionComponent from './components/QuestionComponent.vue';
import {addAnswerRecordAPI, addAnswerSessionAPI, getAiNextQuestionAPI} from "@/api/question";
import type {API} from "@/type/type";
import AiGenerating from "@/components/AiGenerating/AiGenerating.vue";

const router = useRouter();

// 模拟题目数据
const currentQuestion = ref<API.INextQuestion | null>(null);

const currentAnswer = ref<string | string[] | null>(null);
const showCorrect = ref(false);
const showExplanationPopup = ref(false);
const showCompletionDialog = ref(false);
const loading = ref(false);


// 方法
const goBack = () => {
  router.go(-1);
};

const goToResult = () => {
  router.push('/practice/result');
};

const handleAnswerUpdate = (answer: string | string[]) => {
  currentAnswer.value = answer;
};

const formatAnswer = (answer: string | string[] | undefined) => {
  if (!answer) return '答案缺失';
  return Array.isArray(answer) ? answer.join('、') : answer;
};

const checkAnswer = () => {
  if (!currentAnswer.value) return;

  isAnswerCorrect();
  showCorrect.value = true;
};

const isAnswerCorrect = (): boolean => {
  if (!currentAnswer.value) return false;

  const correctAnswer = currentQuestion.value?.answers;
  if (!correctAnswer) {
    return false
  }

  if (Array.isArray(currentAnswer.value)) {
    // 多选题判断
    if (!Array.isArray(correctAnswer)) return false;
    if (currentAnswer.value.length !== correctAnswer.length) return false;

    return currentAnswer.value.every(
        (ans, index) => ans === correctAnswer[index]
    );
  } else {
    // 单选题判断
    return correctAnswer.includes(currentAnswer.value);
  }
};

const goNextQuestion = async () => {
  loading.value = true;
  const {data} = await getAiNextQuestionAPI()
  if (!data) {
    showConfirmDialog({
      title: '系统繁忙',
      message: '系统繁忙，请稍后再试  ',
    }).then(async () => {
      router.go(-1);
    }).catch(() => {
      router.go(-1);
    });
  } else {
    currentQuestion.value = data;
  }
  currentAnswer.value = null;
  showCorrect.value = false;

  if (currentQuestion.value?.isLast && currentQuestion.value?.isLast === '0') {
    showCompletionDialog.value = true;
  }
  loading.value = false;
};

const showExplanation = () => {
  showExplanationPopup.value = true;
};

onMounted(async () => {
  await goNextQuestion()
})
</script>

<style lang="less">
.practice-page {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background: linear-gradient(135deg, #f6f8fc 0%, #f0f4f8 100%);

  :deep(.van-nav-bar) {
    background: linear-gradient(135deg, #1989fa 0%, #39b9f9 100%);
    
    .van-nav-bar__title,
    .van-nav-bar__text,
    .van-icon {
      color: #fff;
    }
  }

  .action-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 16px 20px;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
    z-index: 100;
    display: flex;
    gap: 12px;
    
    .van-button {
      flex: 1;
      height: 44px;
      font-size: 16px;
      font-weight: 500;
      border-radius: 22px;
      transition: all 0.3s ease;
      
      &:active {
        transform: scale(0.98);
      }
      
      &--primary {
        background: linear-gradient(135deg, #1989fa 0%, #39b9f9 100%);
        border: none;
        box-shadow: 0 4px 12px rgba(25, 137, 250, 0.2);
        
        &:active {
          box-shadow: 0 2px 8px rgba(25, 137, 250, 0.15);
        }
        
        &--disabled {
          background: #e8e8e8;
          color: #999;
          box-shadow: none;
        }
      }
      
      &--plain {
        color: #1989fa;
        background: transparent;
        border: 1px solid #1989fa;
        
        &:active {
          background: rgba(25, 137, 250, 0.05);
        }
      }
    }
  }

  .explanation-container {
    padding: 20px;
    height: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    background: #fff;

    h3 {
      margin: 0 0 20px;
      text-align: center;
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }

    .explanation-content {
      flex: 1;
      margin: 0 0 20px;
      overflow-y: auto;
      padding: 0 4px;

      p {
        margin-bottom: 16px;
        line-height: 1.6;
        color: #666;
        
        strong {
          color: #333;
          margin-right: 8px;
        }
      }
    }

    .explanation-actions {
      flex-shrink: 0;
      
      .van-button {
        height: 44px;
        font-size: 16px;
        border-radius: 22px;
      }
    }
  }

  .completion-content {
    padding: 24px;
    text-align: center;
    
    p {
      font-size: 16px;
      color: #333;
      margin: 12px 0;
      
      &:last-child {
        color: #1989fa;
        font-size: 20px;
        font-weight: 500;
      }
    }
  }
}

.ai-loading {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.98);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
